import React, {
  forwardRef,
  useEffect,
  useImperativeHandle,
  useRef,
  useState,
} from 'react';
import {
  Divider,
  Form,
  Input,
  Modal,
  Steps,
  Select,
  Message,
} from '@arco-design/web-react';
import {
  addLessonApi,
  getAllDicApi,
  getDicValueApi,
  getLessonsApi,
  getTreeApi,
  updateLessonApi,
} from '@/request/api';
const Step = Steps.Step;
const FormItem = Form.Item;
const TextArea = Input.TextArea;

const Option = Select.Option;

const LessonFormModal = forwardRef(
  (
    props: {
      cancelBackToRefresh;
    },
    ref
  ) => {
    const [visible, setVisible] = useState(false); // table
    const [step, setStep] = useState(1);

    useImperativeHandle(ref, () => ({
      changeVal: (newVal) => {
        setVisible(newVal);
      },
      setUpdateId: (newVal) => {
        setUpdateId(newVal);
      },
      setFormData: (newVal) => {
        form.setFieldsValue(newVal);
      },
      resetFormData: () => {
        form.resetFields();
      },
    }));

    const [form] = Form.useForm();
    const formRef = useRef();
    const [formData, setFormData] = useState({ deptId: [] });
    const [updateId, setUpdateId] = useState();
    const [sysDepts, setSysDepts] = useState([]); //院校
    const [major, setMajor] = useState([]); //专业
    const [courseType, setCourseType] = useState([]); //课程类型
    const [semester, setSemester] = useState([]); //学期
    const [courseSystemType, setCourseSystemType] = useState([]); //课程体系
    const [teachers, setTeachers] = useState([]); //课程体系
    const [lessons, setLessons] = useState([]); //先修课程、支持课程

    useEffect(() => {
      fetchDeptAndMajor();
      fetchCourseType();
      fetchSemester();
      fetchCourseSystemType();
      fetchLessons();
      fetchTeachers();
    }, []);

    const fetchTeachers = () => {
      getAllDicApi({
        sysRoleId: 2,
      })
        .then((res) => {
          const { data } = res;
          setTeachers(data);
        })
        .catch((e) => {
          console.log(e);
        });
    };

    const fetchDeptAndMajor = () => {
      getTreeApi()
        .then((res) => {
          const { data } = res;
          const depts = [];
          const majors = [];

          data.map((dept) => {
            depts.push(dept);
            dept.children.map((major) => {
              majors.push(major);
            });
          });
          setSysDepts(depts);
          setMajor(majors);
        })
        .catch((e) => {
          console.log(e);
        });
    };

    const fetchCourseType = () => {
      getDicValueApi({ code: 'course_type' })
        .then((res) => {
          const { data } = res;
          setCourseType(data);
        })
        .catch((e) => {
          console.log(e);
        });
    };

    const fetchSemester = () => {
      getDicValueApi({ code: 'semester' })
        .then((res) => {
          const { data } = res;
          setSemester(data);
        })
        .catch((e) => {
          console.log(e);
        });
    };

    const fetchCourseSystemType = () => {
      getDicValueApi({ code: 'course_system_type' })
        .then((res) => {
          const { data } = res;
          setCourseSystemType(data);
        })
        .catch((e) => {
          console.log(e);
        });
    };

    const fetchLessons = () => {
      getLessonsApi({})
        .then((res) => {
          const { data } = res;
          setLessons(data);
        })
        .catch((e) => {
          console.log(e);
        });
    };

    const onValuesChange = (changeValue, values) => {
      setFormData(values);
    };

    const onOK = async () => {
      try {
        await form.validate();
        if (updateId) {
          updateLessonApi({ id: updateId, ...formData })
            .then((res) => {
              const { msg } = res;
              Message.success(msg);
              setVisible(false);
              props.cancelBackToRefresh();
            })
            .catch((e) => {
              console.log(e);
            });
        } else {
          addLessonApi({ ...formData })
            .then((res) => {
              const { msg } = res;
              Message.success(msg);
              setVisible(false);
              props.cancelBackToRefresh();
            })
            .catch((e) => {
              console.log(e);
            });
        }
      } catch (e) {}

      // if (step === 1) {
      //   setStep(2);
      // }
      // if (step === 2) {
      //   setStep(3);
      // }
      // if (step === 3) {
      //   setVisible(false);
      // }
      // setVisible(false);
    };

    return (
      <Modal
        title="课程信息"
        visible={visible}
        // okText={step === 3 ? '确定' : '下一步'}
        onOk={onOK}
        onCancel={() => setVisible(false)}
      >
        {/*<div style={{ padding: '16px 0' }}>*/}
        {/*  <Steps*/}
        {/*    size="small"*/}
        {/*    lineless*/}
        {/*    current={step}*/}
        {/*    style={{ maxWidth: 375, margin: '0 auto' }}*/}
        {/*  >*/}
        {/*    <Step title="Succeeded" />*/}
        {/*    <Step title="Processing" />*/}
        {/*    <Step title="Pending" />*/}
        {/*  </Steps>*/}
        {/*</div>*/}
        {/*<Divider style={{ margin: 0 }} />*/}

        <Form
          autoComplete="off"
          form={form}
          ref={formRef}
          onValuesChange={onValuesChange}
        >
          <FormItem
            label="课程名称"
            field="name"
            rules={[
              { required: true, message: '课程名称是必填项' },
              {
                validator(value, cb) {
                  if (value.length === 0) {
                    return cb('课程名称必须填写');
                  }
                  return cb();
                },
              },
            ]}
          >
            <Input placeholder="请输入课程名称" />
          </FormItem>
          <FormItem
            label="所属院校"
            field="sysDeptId"
            rules={[
              { required: true, message: '所属院校是必填项' },
              {
                validator(value, cb) {
                  if (value.length === 0) {
                    return cb('所属院校必须填写');
                  }
                  return cb();
                },
              },
            ]}
          >
            <Select placeholder="下拉选择" allowClear>
              {sysDepts.map((option, index) => (
                <Option key={option.id} value={option.id}>
                  {option.name}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem
            label="所属专业"
            field="sysSpecialityDeptIds"
            rules={[
              { required: true, message: '所属专业是必填项' },
              {
                validator(value, cb) {
                  if (value.length === 0) {
                    return cb('所属专业必须填写');
                  }
                  return cb();
                },
              },
            ]}
          >
            <Select mode="multiple" placeholder="下拉选择" allowClear>
              {major.map((option, index) => (
                <Option key={option.id} value={option.id}>
                  {option.name}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem
            label="是否必修"
            field="required"
            rules={[
              { required: true, message: '是否必修是必填项' },
              {
                validator(value, cb) {
                  if (value.length === 0) {
                    return cb('是否必修必须填写');
                  }
                  return cb();
                },
              },
            ]}
          >
            <Select placeholder="下拉选择" allowClear>
              <Option key={1} value={1}>
                必修
              </Option>
              <Option key={0} value={0}>
                不必修
              </Option>
            </Select>
          </FormItem>
          <FormItem
            label="课程类型"
            field="courseType"
            rules={[
              { required: true, message: '课程类型是必填项' },
              {
                validator(value, cb) {
                  if (value.length === 0) {
                    return cb('课程类型必须填写');
                  }
                  return cb();
                },
              },
            ]}
          >
            <Select placeholder="下拉选择" allowClear>
              {courseType.map((option, index) => (
                <Option key={option.key} value={option.key}>
                  {option.value}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label="学期" field="semester">
            <Select placeholder="下拉选择" allowClear>
              {semester.map((option, index) => (
                <Option key={option.key} value={option.key}>
                  {option.value}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label="课程体系" field="courseSystemType">
            <Select placeholder="下拉选择" allowClear>
              {courseSystemType.map((option, index) => (
                <Option key={option.key} value={option.key}>
                  {option.value}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem
            label="课程学时"
            field="classHour"
            normalize={(value) => {
              return value * 1;
            }}
          >
            <Input type={'number'} placeholder="请输入课程名称" />
          </FormItem>
          <FormItem
            label="课程学分"
            field="credit"
            normalize={(value) => {
              return value * 1;
            }}
          >
            <Input type={'number'} placeholder="请输入课程名称" />
          </FormItem>
          {/*<FormItem label="课程教师" field="teacherIdList">*/}
          {/*  <Select mode="multiple" placeholder="下拉选择" allowClear>*/}
          {/*    {teachers.map((option, index) => (*/}
          {/*      <Option key={option.key} value={option.key}>*/}
          {/*        {option.value}*/}
          {/*      </Option>*/}
          {/*    ))}*/}
          {/*  </Select>*/}
          {/*</FormItem>*/}
          <FormItem label="先修课程" field="preCoursesId">
            <Select mode="multiple" placeholder="下拉选择" allowClear>
              {lessons.map((option, index) => (
                <Option key={option.key} value={option.key}>
                  {option.value}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label="支持课程" field="supportCoursesId">
            <Select mode="multiple" placeholder="下拉选择" allowClear>
              {lessons.map((option, index) => (
                <Option key={option.key} value={option.key}>
                  {option.value}
                </Option>
              ))}
            </Select>
          </FormItem>
          <FormItem label="课程简介" field="introduce">
            <TextArea placeholder="请输入课程简介" style={{ minHeight: 64 }} />
          </FormItem>
        </Form>
      </Modal>
    );
  }
);

export default LessonFormModal;
